import { Button, Drawer, DrawerProps, Form, Input, Select, Spin } from 'antd';
import { memo, useEffect, useImperativeHandle } from 'react';
import { QueryObserverResult, RefetchOptions, RefetchQueryFilters } from 'react-query';
import { IFormRef, IPage } from '../../../types';
import { useForm } from 'antd/es/form/Form';
import { ISysRole, useAddSysRole, useUpdateSysRole } from '../../../service/sys-role-service';


type IUnitFormParams = {
    open: boolean;
    onRef: React.MutableRefObject<IFormRef | undefined>;
    refetch: <TPageData>(options?: (RefetchOptions & RefetchQueryFilters<TPageData>) | undefined) => Promise<QueryObserverResult<IPage<ISysRole>, unknown>>
    openFn: (open: boolean) => void;
    sysRole?: ISysRole;
} & DrawerProps;


const SysRoleForm = ({ sysRole, ...props }: IUnitFormParams) => {
    useEffect(() => {
        console.log("SysRoleForm")
    })
    const [form] = useForm();
    const { mutateAsync: addSysRoleMutation, isLoading: addIsLoading } = useAddSysRole();
    const { mutateAsync: updateSysRoleMutation, isLoading: UIsLoading } = useUpdateSysRole();
    useEffect(() => {
        form.setFieldsValue({
            sysRoleName: sysRole?.sysRoleName,
            sysRoleId: sysRole?.sysRoleId,
            sysRolePermisstion: sysRole?.sysRolePermisstion
        });
    }, [sysRole]);

    /**
   * 更新方法
   */
    const updateHandler = async () => {
        const values = form.getFieldsValue();
        await updateSysRoleMutation({ sysRoleId: sysRole?.sysRoleId, ...values });
        props.refetch();
        props.openFn(false);
        form.resetFields();
    }

    /**
     * 保存方法
     */
    const saveHandler = async () => {
        const isPass = form.validateFields();
        if (!isPass) {
            return
        }
        const values = form.getFieldsValue();
        await addSysRoleMutation({ ...values });
        props.refetch();
        props.openFn(false);
        form.resetFields();
    }

    /**
     * 向外暴露表单的保存和修改
     */
    useImperativeHandle(props.onRef, () => ({
        reset: () => {
            form.resetFields();
        },
        save: () => {
            saveHandler();
        },
        update: async () => {
            updateHandler();
        }
    }));

    return (
        <Drawer title={'角色'} placement="right" width={'35rem'} closable={true} onClose={() => props.openFn(false)} forceRender={true} open={props.open} footer={
            <>
                {
                    sysRole ? (
                        <Button onClick={() => { updateHandler(); }}>
                            修改
                        </Button>
                    ) : (
                        <Button onClick={() => { saveHandler(); }}>
                            保存
                        </Button>
                    )
                }
            </>
        }>
            <Spin spinning={addIsLoading || UIsLoading}>
                <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
                    <Form.Item label={'角色名称'} name={'sysRoleName'} rules={[{ required: true, message: '角色名称不能为空' }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label={'角色权限'} name={'sysRolePermisstion'} rules={[{ required: true, message: '角色权限不能为空' }]}>
                        <Input />
                    </Form.Item>
                </Form>
            </Spin>
        </Drawer>
    );
};


export default memo(SysRoleForm)